package com.sunchangpeng.wechat.mp.stat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.sunchangpeng.wechat.mp.EndpointProvider;
import com.sunchangpeng.wechat.mp.MpAppSetting;
import com.sunchangpeng.wechat.mp.MpWechatClientFactory;
import lombok.Data;

import java.time.LocalDate;
import java.util.List;

public class UserStats extends Stats {
    public static UserStats with(MpAppSetting appSetting) {
        UserStats stats = new UserStats();
        stats.setWechatClient(MpWechatClientFactory.getInstance().with(appSetting));
        return stats;
    }

    /**
     * 获取用户增减数据
     */
    public List<UserSummary> getUserSummary(LocalDate start, LocalDate end) {
        if (diffThanDays(start, end, 6)) {
            throw new IllegalArgumentException("start和end相差不能超过6天以上");
        }

        String url = EndpointProvider.get("url.stats.user.summary");
        return JSON.parseObject(doRequest(url, start, end), UserSummaryWrapper.class).getList();
    }

    /**
     * 获取累计用户数据
     */
    public List<UserCumulative> getUserCumulative(LocalDate start, LocalDate end) {
        if (diffThanDays(start, end, 6)) {
            throw new IllegalArgumentException("start和end相差不能超过6天以上");
        }

        String url = EndpointProvider.get("url.stats.user.cumulative");
        return JSON.parseObject(doRequest(url, start, end), UserCumulativeWrapper.class).getList();
    }

    @Data
    public static class UserCumulative {
        @JSONField(name = "ref_date")
        private String date;

        @JSONField(name = "cumulate_user")
        private int users;
    }

    @Data
    public class UserSummary {
        @JSONField(name = "ref_date")
        private String date;
        @JSONField(name = "user_source")
        private int sourceUsers;
        @JSONField(name = "new_user")
        private int newUsers;
        @JSONField(name = "cancel_user")
        private int canceledUsers;
    }

    @Data
    public static class UserSummaryWrapper {
        private List<UserSummary> list;
    }

    @Data
    public static class UserCumulativeWrapper {
        private List<UserCumulative> list;
    }

}
